var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var { userModel, pubModel } = require('../model/db')
var multiparty = require('multiparty');

let { AlipaySdk } = require("alipay-sdk")
//沙箱支付 4版本
router.post("/alipaySdk", async (req, res) => {
  let { out_trade_no, subject, total_amount } = req.body
  // 实例化客户端
  const alipaySdk = new AlipaySdk({
    // 设置应用 ID
    appId: '2021000148621186',
    // 设置应用私钥
    privateKey: "MIIEogIBAAKCAQEAgzLX+FkEjAg+LkJ6MVb1pRywn8O3aBrsPa3urtey2Kif7nmwCq1m4SLamkj/7Wv2Xd/YPe80BXyvyfVnE4czqYww8wI6UJ3piGHCu0QbdhJfAUDymMgTqUYyC4RaXlE8/Aev2p0KFdudc5t3X17n/CJK2iV/rIRcDp+CbDx+yeb9i2MPtoJDjJN/jjOrbqTDm6Xh6Lyv7nEpxP1hk82NrOgEK3kAB3jwrAcx3yMSDKWIxGO4oQx2Nmdcpq7O1GnwE1BzfO4Eakzl3TCnxjIOTTo84f/tzR8VLRUBmgfksEyp0e4AzECd+mksmVyeVpaJ67yKrr2bN5y29ZrMM/ur+QIDAQABAoIBAAwcCEUa6kmGhT690gt1zEyGHmNQrEAGpCF5SVuH+zD2N3TKdI43vRQwpF6zODQQz/eQLqRgzLto68zHQtFRnFoc33O+k+VW/fQhmdixC5vVTEGQXhPt+6qXGQ1pFPI5q1hT2U5jSkgEMj82bUk3OFBUVfZWmbcxrFGJNX+KAeXes1aw0fCol2qMKsaI94wXWXWpls/IMkwQIZ2CAVkjq0xma9rYVUviDRsDSqEXhnLJq0y15J7x+m6UwEIW4+7TqnNOxE/BFAMnBEaEHa3Ju0z4dYs+V2um14xnf/4+WNJYMCOkDPhe+JYsNdl+8TutQh7h2FTLOkx7UsE1FmlrzAECgYEAu/kJkd4mpwfUCl20xmvIqv58vkntWTY63mrO5tZAn4rB9RXNeD03X+2rkRxUsMLFEmQh5GA2rNR8/A1PiBZqMpif4diKDF5s54IUQX8/uQ163tfEIWr8dACZ1Mu8Kukz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VIEm7kof5QrJoMlVm3h7FL+GVoNljezADr3+FmLMw6ljP7EdtGrrA26+rSLF03uohDGum6v7RUnUbCjgES2ySdwIDAQAB",
    // 密钥类型，请与生成的密钥格式保持一致，参考平台配置一节
    // keyType: 'PKCS1',
    // 设置网关地址，默认是 https://openapi.alipay.com
    "gateway": "https://openapi-sandbox.dl.alipaydev.com/gateway.do"
  });

  const bizContent = {
    out_trade_no: out_trade_no,
    product_code: "FAST_INSTANT_TRADE_PAY",//支付信息的订单编号 前端在确定订单的时候会生产订单信息 包括订单编号
    subject: subject,//支付信息中的商品名称
    body: "234",
    total_amount: total_amount,//支付金额
  };

  const html = await alipaySdk.pageExecute('alipay.trade.wap.pay', 'POST', {
    bizContent,
    returnUrl: 'https://example.com/payment_success'
    // returnUrl: 'alipay://payment_success'  // 使用特殊协议作为标识
  });

  res.send(html);

})
//登录
router.post("/login", async (req, res) => {
  const user = req.body
  let userList = await userModel.find(user)
  var token = jwt.sign({ userList: userList.userName }, 'shhhhh');
  if (userList.length > 0) {
    res.send({
      code: 200,
      msg: "登录成功",
      token
    })
  } else {
    res.send({
      code: 404,
      msg: "用户名或密码错误"
    })
  }
})
//图片上传
//上传图片的路由
router.post('/upload', (req, res) => {
  //配置multiparty  用来接受上传的文件
  //1.创建multiparty提供的表单对象
  let form = new multiparty.Form()
  //2.为multiparty配置目标路径   upload
  form.uploadDir = 'upload'
  //3.接受上传的文件  
  //  三个参数 
  //  err：错误的对象 程序出错err就是一个对象 
  //  files:表示普通的表单数据 非前后端分离会用到  (现在前后端分离用不到)
  //imgfile:上传图片的信息
  form.parse(req, (err, files, imgfile) => {  //回调函数
    // console.log(files,"aaa");
    // console.log(imgfile,"imgfile");  //详细信息
    //将上传到服务器上的图片路径返回 
    res.send({
      // path:imgfile.file[0].path,
      path: 'http://localhost:3005/' + imgfile.file[0].path,  // 返回服务器上的图片路径(返回绝对路径)
    })
  })
});

//获取数据
router.post('/pub', async (req, res) => {
  let { currentPage, pageSize, sortField, sortOrder } = req.body
  //搜索
  let arr = []
  // if (carName != "") {
  //   arr.push({ title: { $regex: carName } })
  // }
  // if (carSort != "不限") {
  //   arr.push({ brand: { $regex: carSort } })
  // }
  // const a = price.split('-')
  // const min = a[0]
  // const max = a[1]
  // if (price != "不限") {
  //   arr.push({ price: { $gte: min, $lte: max } })
  // }

  //排序
  let sort = {};
  if (sortField && sortOrder) {
    sort[sortField] = sortOrder === 'asc' ? 1 : -1;
  }

  // 1 表示升序，-1 表示降序
  // let pubList = await pubModel.find({ $and: arr }).sort({ createdAt: 1 }).skip((currentPage - 1) * pageSize).limit(pageSize);

  let pubList = await pubModel.find({ $and: arr }).skip((currentPage - 1) * pageSize).limit(pageSize).sort(sort)
  let total = await pubModel.countDocuments({ $and: arr })
  res.send({
    code: 200,
    pubList,
    total
  })
})

//添加
router.post('/add', async (req, res) => {
  let pubList = req.body
  pubModel.create(pubList)
  res.send({
    code: 200,
    msg: "添加成功"
  })
})
//修改
router.post('/update', async (req, res) => {
  let pubList = req.body
  await pubModel.updateOne({ _id: pubList._id }, pubList)
  res.send({
    code: 200,
    msg: "修改成功"
  })
})

//删除
router.post('/del', async (req, res) => {
  let { _id } = req.body
  await pubModel.deleteOne({ _id })
  res.send({
    code: 200,
    msg: "删除成功"
  })
})
//批量删除
router.post('/batch', async (req, res) => {
  let { arr } = req.body
  await pubModel.deleteMany({ _id: arr })
  res.send({
    code: 200,
    msg: "删除成功"
  })
})
//回显
router.post("/alone", async (req, res) => {
  let { _id } = req.body
  let list = await addrModel.find({ _id })
  res.send({
    code: 200,
    list
  })
})

//批量改变状态
router.post('/batch_status', async (req, res) => {
  let { ids, status } = req.body
  console.log(ids, status);
  await pubModel.updateMany({ _id: ids }, { status: status })
  res.send({
    code: 200,
    msg: "删除成功"
  })
})
module.exports = router;
